package com.profgj.profgj.controller;

import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.utils.TaskService;
import com.profgj.profgj.verifycode.VerifyCode;
import com.profgj.profgj.vo.EmptyObject;
import com.profgj.profgj.vo.ResultMsg;
import com.profgj.profgj.vo.ShortMessage;
import com.profgj.profgj.vo.TaskMgr;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * 验证码
 */
@Controller
@Api(tags = {"验证码生成"}, description = "验证码访问,获取")
public class VerifyCodeController {

    /**
     * 任务短信服务对象
     */
    @Resource
    private TaskService taskService;

    /**
     * 返回空对象的替代品
     */
    private EmptyObject emptyObject = new EmptyObject();


    /**
     * 验证码获取
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/verifycode")
    @ApiOperation(value = "验证码生成")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public void code(HttpServletResponse response,HttpServletRequest request) throws IOException {

        try {

            // 图片宽高
            int width=200;
            int height=69;

            // 生成图片缓冲区
            BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

            //生成对应宽高的初始图片
            String randomText = VerifyCode.drawRandomText(width,height,verifyImg);

            //单独的一个类方法，出于代码复用考虑，进行了封装。
            //功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
            request.getSession().setAttribute("verifyCode", randomText);
            //必须设置响应内容类型为图片，否则前台不识别
            response.setContentType("image/png");
            //获取文件输出流
            OutputStream os = response.getOutputStream();
            //输出图片流
            ImageIO.write(verifyImg,"png",os);
            os.flush();
            //关闭流
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取出验证码并发短信
     * @param phoneNumber       手机号
     * @param session           会话session
     * @return
     */
    @GetMapping("/phoneverifycode")
    @ApiOperation(value = "取出验证码并发短信")
    @ApiImplicitParam(name = "phoneNumber", value = "手机号",required = true, dataType = "String", paramType = "String")
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> sendPhoneVerifyCode(String phoneNumber,@ApiIgnore HttpSession session){
        // 参数校验
        if(!EmptyUtils.isStringEmpty(phoneNumber)){
            return ReturnOperator.createResultMsg("", "手机号不能为空", ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 图片宽高
        int width=200;
        int height=69;
        // 创建图片缓冲区
        BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //生成对应宽高的初始图片并取出验证码
        String randomText = VerifyCode.drawRandomText(width,height,verifyImg);
        // 将验证码加入session中
        session.setAttribute("phoneverifycode",randomText);

        System.out.println("短信验证码已生成:"+randomText + "\t已经加入session中");

        // 校验session中的验证码
        if(!EmptyUtils.isStringEmpty(randomText)){
            return ReturnOperator.createResultMsg("", "验证码过期", ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 构造发送短信对象
        TaskMgr taskMgr = new TaskMgr();
        taskMgr.setPhoneNumber(phoneNumber);
        taskMgr.setContent("验证码:"+randomText);
        // 发送短信
        ShortMessage shortMessage = taskService.sendMessage(taskMgr);
        // 对比发送后的状态
        if(!"Success".equalsIgnoreCase(shortMessage.getReturnstatus())){
            // 短信发送失败返回
            return ReturnOperator.createResultMsg("", "短信发送失败", ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回结果
        return ReturnOperator.createResultMsg("短信验证码发送成功", "", ServerStatus.OK,
                new ArrayList(), emptyObject, HttpStatus.OK);
    }
}
